package com.kokomi.handler;

import com.kokomi.pojo.Book;
import com.kokomi.pojo.RedisConst;
import com.kokomi.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class StorageRunner implements CommandLineRunner {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    BookService bookService;


    @Override
    public void run(String... args) throws Exception {
        // 1.redis中获取库存的key，判断是否存在
        Boolean key = redisTemplate.hasKey(RedisConst.BOOK_STORAGE);

        if(!key){
            // 2.如果不存在
            // 2.1 从数据库中查询所有的书本的库存
            List<Book> list = bookService.list();
            for (Book book : list){
                redisTemplate.opsForHash().put(RedisConst.BOOK_STORAGE,book.getId().toString(),book.getStoreCount());
            }
            log.info("初始化库存成功");
        }


    }
}
